package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao groupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrDao attrDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveDetail(AttrVo attrVo) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, entity);
        this.save(entity); //1.保存基本信息

        if (attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(entity.getAttrId());
            relationDao.insert(relationEntity);//2.保存属性和属性分组信息
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, String attrType, Long catelogId) {
        int attrTypeValue = "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", attrTypeValue);
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }

        if (catelogId != 0) {
            queryWrapper.and((obj -> {
                obj.eq("catelog_id", catelogId);
            }));
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((item) -> {
            AttrRespVo vo = new AttrRespVo();
            BeanUtils.copyProperties(item, vo);

            //1.设置所属分组名称
            AttrGroupEntity groupInfo = getAttrGroupInfo(item.getAttrId());
            if (groupInfo != null) {
                vo.setAttrGroupId(groupInfo.getAttrGroupId());
                vo.setGroupName(groupInfo.getAttrGroupName());
            }

            //2.设置所属分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());
            if (categoryEntity != null) {
                vo.setCatelogName(categoryEntity.getName());
            }

            return vo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    /**
     * 获取属性信息
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);

        //1.设置分组信息
        AttrGroupEntity groupInfo = getAttrGroupInfo(attrId);
        if (groupInfo != null) {
            respVo.setAttrGroupId(groupInfo.getAttrGroupId());
            respVo.setGroupName(groupInfo.getAttrGroupName());
        }

        //2.设置分类信息
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }

    @Transactional
    @Override
    public void updateDetail(AttrVo attrVo) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, entity);
        this.updateById(entity);

        //1.修改分组关联
        if (attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrVo.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if (count > 0) {//更新
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            } else {//新增
                relationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id获取关联的属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        if (relationEntities != null) {
            List<Long> ids = relationEntities.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            if (ids != null && ids.size() > 0) {
                return this.listByIds(ids);
            }
        }

        return null;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, entity);
            return entity;
        }).collect(Collectors.toList());

        if (entities != null && entities.size() > 0) {
            relationDao.deleteBatchRelation(entities);
        }
    }

    /**
     * 获取当前分组没有关联的所有属性
     * 1、当前分组只能关联自己所属分类的属性
     *
     * 2、当前分组只能关联别的分组没有引用的属性
     * 1）当前分类下的所有分组信息
     * 2）这些分组关联的属性
     * 3）从当前分类的所有属性中剔除这些属性
     *
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        AttrGroupEntity attrGroupEntity = groupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        //1）当前分类下的所有分组信息
        List<AttrGroupEntity> groupEntities = groupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> groupIds = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        if (groupIds != null && groupIds.size() > 0) {
            //2）这些分组关联的属性
            List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
            List<Long> otherGroupRelationAttrIds = relationEntities.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            if (otherGroupRelationAttrIds != null && otherGroupRelationAttrIds.size() > 0) {
                //3）从当前分类的所有属性中剔除这些属性
                QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).eq("catelog_id",catelogId).notIn("attr_id", otherGroupRelationAttrIds);
                String key = (String)params.get("key");
                if(!StringUtils.isEmpty(key)){
                    queryWrapper.and((obj)->{
                        obj.eq("attr_id",key).or().like("attr_name",key);
                    });
                }
                IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

                PageUtils pageUtils = new PageUtils(page);
                return pageUtils;
            }
        }

        return null;

    }

    /**
     * 根据属性id获取属性分组信息
     *
     * @param attrId
     * @return
     */
    private AttrGroupEntity getAttrGroupInfo(Long attrId) {
        AttrGroupEntity attrGroupEntity = null;
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null) {
            attrGroupEntity = new AttrGroupEntity();
            attrGroupEntity.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity groupEntity = groupDao.selectById(relationEntity.getAttrGroupId());
            if (groupEntity != null) {
                attrGroupEntity.setAttrGroupName(groupEntity.getAttrGroupName());
            }
        }

        return attrGroupEntity;
    }
}